﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using shfa.snomtastic.data;
using shfa.snomtastic.data.business;
using shfa.snomtastic.data.ip;
using shfa.snomtastic.data.security;


namespace shfa.snomtastic.root
{
    public partial class register : System.Web.UI.Page
    {
        public string host { get; set; }
        public string appPath { get; set; }
        public string macAddress { get; set; }
        public string ipAddress { get; set; }
        public string userAgent { get; set; }
        public bool canGetPassword { get; set; }
        
        public string http_client_user { get; set; }
        public string http_client_pass { get; set; }

        public AppConfig ac = new AppConfig();


        protected void Page_Load(object sender, EventArgs e)
        {

            macAddress = Request.QueryString["mac"];
            ipAddress = Request.UserHostAddress;
            userAgent = Request.ServerVariables["HTTP_USER_AGENT"];
            canGetPassword = false;

            captureRequest();

            PhoneController pc = new PhoneController();
            PhoneInfo pi = pc.SelectPhoneByMacAddress(macAddress);
            if (pi != null)
            {
                RijndaelEnhanced re = new RijndaelEnhanced();
                http_client_user = pi.PhoneId.ToString();
                http_client_pass = re.Decrypt(pi.HttpClientPass);
            }

        }

        protected void Page_PreRender(object sender, EventArgs e)
        {

            Response.ContentType = "text/xml";
            Response.ContentEncoding = Encoding.UTF8;

            using (TextWriter textWriter = new StreamWriter(Response.OutputStream, Encoding.UTF8))
            {

                XmlWriterSettings writerSettings = new XmlWriterSettings();
                writerSettings.OmitXmlDeclaration = false;
                writerSettings.CloseOutput = true;

                XmlWriter xmlWriter = XmlTextWriter.Create(textWriter, writerSettings);

                //Write the settings
                xmlWriter.WriteStartElement("phone-settings");

                if (canGetPassword)
                {
                    xmlWriter.WriteStartElement("http_client_user");
                    xmlWriter.WriteAttributeString("perm", "");
                    xmlWriter.WriteValue(http_client_user);
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("http_client_pass");
                    xmlWriter.WriteAttributeString("perm", "");
                    xmlWriter.WriteValue(http_client_pass);
                    xmlWriter.WriteEndElement();
                }

                xmlWriter.WriteStartElement("settings_refresh_timer");
                xmlWriter.WriteAttributeString("perm", "");
                xmlWriter.WriteValue(ac.Items["failModeDelay"]);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("firmware_status");
                xmlWriter.WriteAttributeString("perm", "");
                xmlWriter.WriteValue(ac.Items["siteRoot"] + "phone/firmware.aspx?mac=" + macAddress);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("firmware_interval");
                xmlWriter.WriteAttributeString("perm", "");
                xmlWriter.WriteValue("1");
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("update_policy");
                xmlWriter.WriteAttributeString("perm", "");
                xmlWriter.WriteValue("auto_update");
                xmlWriter.WriteEndElement();
                
                xmlWriter.WriteStartElement("challenge_reboot");
                xmlWriter.WriteAttributeString("perm", "");
                xmlWriter.WriteValue("off");
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("setting_server");
                xmlWriter.WriteAttributeString("perm", "");
                xmlWriter.WriteValue(ac.Items["siteRoot"] + "phone/phone.aspx?mac={mac}");
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndElement();
                xmlWriter.Close();

            }

        }

        private void captureRequest()
        {

            PhoneController pc = new PhoneController();
            PhoneInfo pi = new PhoneInfo();
            bool bNew = false;

            RijndaelEnhanced re = new RijndaelEnhanced();

            if (macAddress != null & macAddress != string.Empty)
            {

                pi = pc.SelectPhoneByMacAddress(macAddress);
                if (pi == null)
                {
                    bNew = true;
                    pi = new PhoneInfo();
                    pi.MacAddress = macAddress;
                    pi.CreatedDate = DateTime.UtcNow;
                    pi.ReRegisterCount = 0;
                }

                pi.UpdatedDate = DateTime.UtcNow;
                pi.UserAgent = userAgent;
                pi.IpAddress = ipAddress;
                pi.SerialNumber = "";

                if (pi.HttpClientPass == null || pi.HttpClientPass == string.Empty)
                {
                    pi.HttpClientPass = re.Encrypt(RandomPass());
                    canGetPassword = true;
                }

                UserAgentInfo ao = new UserAgentInfo(userAgent);
                pi.Model = ao.Model;
                pi.Firmware = ao.Firmware;
                pi.BootLoader = ao.BootLoader;
                pi.Extension = "";

                ModelController mc = new ModelController();
                List<ModelInfo> miList = mc.SelectModels();
                foreach (ModelInfo mi in miList)
                {
                    if (pi.Model == mi.Name)
                        pi.ModelId = mi.ModelId;
                }

                FirmwareController fc = new FirmwareController();
                List<FirmwareInfo> fiList = fc.SelectFirmwares();
                foreach (FirmwareInfo fi in fiList)
                {
                    if (pi.Firmware == fi.Version & pi.ModelId == fi.ModelId)
                    {
                        pi.FirmwareId = fi.FirmwareId;
                    }
                }


                try
                {
                    IPTool ip = new IPTool(ipAddress);
                    Int32 ipInt = (Int32)ip.IPAddressToNumber(ipAddress);

                    SubnetController sc = new SubnetController();
                    List<SubnetInfo> siList = sc.SelectSubnets();
                    foreach (SubnetInfo si in siList)
                    {
                        if (ipInt >= si.StartInt & ipInt <= si.EndInt)
                        {
                            pi.SubnetId = si.SubnetId;
                        }
                    }
                }
                catch { }

                EventLog el = new EventLog();
                if (bNew)
                {

                    Guid newId = pc.InsertPhone(pi);
                    el.LogEvent(newId, new Guid(), macAddress, ipAddress, userAgent, "Phone", "New Phone Registered", "Information");
                }
                else
                {
                    pc.UpdatePhone(pi);
                    el.LogEvent(pi.PhoneId, pi.UserId, macAddress, ipAddress, userAgent, "Phone", "Phone Re-Registered", "Information");
                }
            }
        }

        private string RandomPass()
        {
            Random r = new Random(Convert.ToInt32(DateTime.UtcNow.Ticks & 0x000000007FFFFFFF));
            int passLength = r.Next(10, 15);
            string s = "";
            int n;
            for (int i = 0; i < passLength; i++)
            {
                int range = r.Next(1, 4);
                switch (range)
                {
                    case 1:
                        n = r.Next(48, 58);
                        break;
                    case 2:
                        n = r.Next(65, 91);
                        break;
                    default:
                        n = r.Next(97, 123);

                        break;
                }
                s += Chr(n);
            }

            return s;
        }

        private string Chr(int p_intByte)
        {

            byte[] bytBuffer = new byte[] { (byte)p_intByte };
            return Encoding.GetEncoding(1252).GetString(bytBuffer);

        }


    }
}
